﻿using System;
using System.Text;
using System.Net.Http;
using System.Net.Http.Headers;
using DataProcess.Interface;

namespace DataProcess.Core.Tools
{
    public class HttpHelper
    {
        /// <summary>
        /// HttpClient所有方法是线程安全的, 所以可以只适用一个HttpClient,每次new出来的HttpClient都会占用一个TCP连接,耗费资源
        /// </summary>
        private HttpClient Client { get; set; }

        public HttpHelper()
        {
            Client = new HttpClient() { Timeout = new TimeSpan(0, 0, 0, 10) };
            Client.DefaultRequestHeaders.Connection.Add("keep-alive");
            Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }

        public Tuple<bool, string> SendData(string uri, string jsondata, string author, Interface.HttpRequestType httpType)
        {
            if (string.IsNullOrEmpty(uri)) return new Tuple<bool, string>(false, "传入的地址为空");
            if (!string.IsNullOrEmpty(author))
            {
                if (AuthenticationHeaderValue.TryParse(author, out var parsedValue))
                {
                    Client.DefaultRequestHeaders.Authorization = parsedValue;
                }
                else
                {
                    Client.DefaultRequestHeaders.Authorization = null;
                }
            }

            var httpContent = new StringContent(jsondata, Encoding.UTF8, "application/json");
            HttpResponseMessage response = null;
            try
            {
                switch (httpType)
                {
                    case Interface.HttpRequestType.Post:
                        response = Client.PostAsync(uri, httpContent).Result;
                        break;
                    case Interface.HttpRequestType.Put:
                        response = Client.PutAsync(uri, httpContent).Result;
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                return new Tuple<bool, string>(false, ex.Message);
            }

            if (response == null) return new Tuple<bool, string>(false, $"HttpResponseMessage为null，接口未返回信息");

            if (response.IsSuccessStatusCode)
            {
                string msg = $"{response.StatusCode}{response.Content.ReadAsStringAsync().Result}";
                response.Dispose();
                return new Tuple<bool, string>(true, msg);
            }
            else
            {
                var code = response.StatusCode;
                response.Dispose();
                return new Tuple<bool, string>(false, $"{code}");
            }
        }

        public T Get<T>(string uri, string author = "") where T : class, new()
        {
            if (string.IsNullOrEmpty(uri)) return default;

            if (!string.IsNullOrEmpty(author))
            {
                if (AuthenticationHeaderValue.TryParse(author, out var parsedValue))
                {
                    Client.DefaultRequestHeaders.Authorization = parsedValue;
                }
                else
                {
                    Client.DefaultRequestHeaders.Authorization = null;
                }
            }

            using (HttpResponseMessage response = Client.GetAsync(uri, HttpCompletionOption.ResponseContentRead).Result)
            {
                if (response == null) throw new Exception("回传的HttpResponseMessage为null");

                if (response.IsSuccessStatusCode)
                {
                    if (response.Content == null) throw new Exception("回传的HttpResponseMessage的Content为null，无法解析");
                    var result = response.Content.ReadAsStringAsync().Result;
                    return result.FromJson<T>();
                }
                else
                {
                    throw new Exception("$调用接口失败，回传状态为：{response.IsSuccessStatusCode}");
                }
            }
        }

        public void Dispose()
        {
            Client?.Dispose();
        }
    }
}
